package com.drawingtimer.admin.controller;

import com.drawingtimer.admin.model.entity.TTimeSegmentRecord;
import com.drawingtimer.admin.model.from.TTimeSegmentRecordFrom;
import com.drawingtimer.admin.model.qo.TTimeSegmentRecordQO;
import com.drawingtimer.admin.model.vo.TTimeSegmentRecordPageVO;
import com.drawingtimer.admin.service.TTimeSegmentRecordService;
import com.hccake.ballcat.common.log.operation.annotation.CreateOperationLogging;
import com.hccake.ballcat.common.log.operation.annotation.DeleteOperationLogging;
import com.hccake.ballcat.common.log.operation.annotation.UpdateOperationLogging;
import com.hccake.ballcat.common.model.domain.PageParam;
import com.hccake.ballcat.common.model.domain.PageResult;
import com.hccake.ballcat.common.model.result.BaseResultCode;
import com.hccake.ballcat.common.model.result.R;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;

/**
 * 时间段记录
 *
 * @author jjh 2025-04-24 16:34:17
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/ProductionProcesses/t-time-segment-record")
@Tag(name = "时间段记录管理")
public class TTimeSegmentRecordController {

	private final TTimeSegmentRecordService tTimeSegmentRecordService;

	/**
	 * 分页查询
	 * @param pageParam 分页参数
	 * @param tTimeSegmentRecordQO 时间段记录查询对象
	 * @return R 通用返回体
	 */
	@Operation(summary = "分页查询")
	@GetMapping("/page")
	@PreAuthorize("@per.hasPermission('ProductionProcesses:t-time-segment-record:read')")
	public R<PageResult<TTimeSegmentRecordPageVO>> getTTimeSegmentRecordPage(PageParam pageParam,
			TTimeSegmentRecordQO tTimeSegmentRecordQO) {
		return R.ok(tTimeSegmentRecordService.queryPage(pageParam, tTimeSegmentRecordQO));
	}

	/**
	 * 新增时间段记录
	 * @param tTimeSegmentRecord 时间段记录
	 * @return R 通用返回体
	 */
	@Operation(summary = "新增时间段记录")
	@CreateOperationLogging(msg = "新增时间段记录")
	@PostMapping
	@PreAuthorize("@per.hasPermission('ProductionProcesses:t-time-segment-record:add')")
	public R<Void> save(@RequestBody TTimeSegmentRecord tTimeSegmentRecord) {
		return tTimeSegmentRecordService.save(tTimeSegmentRecord) ? R.ok()
				: R.failed(BaseResultCode.UPDATE_DATABASE_ERROR, "新增时间段记录失败");
	}

	/**
	 * 修改时间段记录
	 * @param tTimeSegmentRecord 时间段记录
	 * @return R 通用返回体
	 */
	@Operation(summary = "修改时间段记录")
	@UpdateOperationLogging(msg = "修改时间段记录")
	@PutMapping
	@PreAuthorize("@per.hasPermission('ProductionProcesses:t-time-segment-record:edit')")
	public R<Void> updateById(@RequestBody TTimeSegmentRecord tTimeSegmentRecord) {
		return tTimeSegmentRecordService.updateById(tTimeSegmentRecord) ? R.ok()
				: R.failed(BaseResultCode.UPDATE_DATABASE_ERROR, "修改时间段记录失败");
	}

	/**
	 * 通过id删除时间段记录
	 * @param id id
	 * @return R 通用返回体
	 */
	@Operation(summary = "通过id删除时间段记录")
	@DeleteOperationLogging(msg = "通过id删除时间段记录")
	@DeleteMapping("/{id}")
	@PreAuthorize("@per.hasPermission('ProductionProcesses:t-time-segment-record:del')")
	public R<Void> removeById(@PathVariable("id") Long id) {
		return tTimeSegmentRecordService.removeById(id) ? R.ok()
				: R.failed(BaseResultCode.UPDATE_DATABASE_ERROR, "通过id删除时间段记录失败");
	}

	/**
	 * 开始计时
	 */
	@Operation(summary = "开始计时")
	@PostMapping("/updateStartTimer")
	public R<Void> updateStartTimer(@RequestBody TTimeSegmentRecordFrom tTimeSegmentRecord) {
		// 获取登录人的姓名id

		return tTimeSegmentRecordService.updateStartTimer(tTimeSegmentRecord) ? R.ok()
				: R.failed(BaseResultCode.UPDATE_DATABASE_ERROR, "报工失败");
	}

	/**
	 * 结束计时
	 */
	@Operation(summary = "结束计时")
	@PostMapping("/updateEndTimer")
	public R<Void> updateEndTimer(@RequestBody TTimeSegmentRecordFrom tTimeSegmentRecord) {
		// 获取登录人的姓名id
		if (tTimeSegmentRecord.getFinishedQuantity() == null
				|| tTimeSegmentRecord.getFinishedQuantity().compareTo(BigDecimal.ZERO) == 0) {
			return R.failed(BaseResultCode.UPDATE_DATABASE_ERROR, "完工数量有误！");
		}
		return tTimeSegmentRecordService.updateEndTimer(tTimeSegmentRecord) ? R.ok()
				: R.failed(BaseResultCode.UPDATE_DATABASE_ERROR, "报工失败");
	}

	@Operation(summary = "获取PLM文件")
	@RequestMapping("/getPlmProgramFile")
	public ResponseEntity<ByteArrayResource> getPlmProgramFile(TTimeSegmentRecordQO qo, HttpServletResponse response) {
		// 设置响应头
		// 调用服务获取 ByteArrayResource
		ByteArrayResource resource = tTimeSegmentRecordService.getPlmProgramFile(qo);

		// 检查资源是否有效
		if (resource == null || resource.getByteArray().length == 0) {
			return ResponseEntity.badRequest().build(); // 或者抛出自定义异常
		}

		// 设置响应头
		HttpHeaders headers = new HttpHeaders();
		headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=sample.pdf");
		headers.add(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate");
		headers.add(HttpHeaders.PRAGMA, "no-cache");
		headers.add(HttpHeaders.EXPIRES, "0");

		// 返回 ResponseEntity
		return ResponseEntity.ok()
			.headers(headers)
			.contentLength(resource.getByteArray().length)
			.contentType(MediaType.APPLICATION_PDF) // 假设是 PDF 文件
			.body(resource);

	}

	@Operation(summary = "获取NC文件")
	@RequestMapping("/getPlmProgramFileNC")
	public R<String> getPlmProgramFileNC(TTimeSegmentRecordQO qo, HttpServletResponse response) {
		return R.ok(tTimeSegmentRecordService.getPlmProgramFileNC(qo));
	}

}